package com.wxx.house;

import com.wxx.util.SeleniumDownloader;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 下载并解析元素
 */
public class HousePriceDownloader extends SeleniumDownloader {
    private static final int CONTRAST_COUNT = 100;
    private int alreadyCount = 0;
    private String currentCityName = "";
    private List<Integer> priceList = new ArrayList<>();
    public List<String> resultList = new ArrayList<>();
    @Override
    public Page download(Request request, Task task) {
        try {
            priceList.clear();
            alreadyCount = 0;
            webDriver.manage().window().setPosition(new Point(400, 20));
            webDriver.get(request.getUrl());
            sleep(6000);
            currentCityName = webDriver.findElement(By.xpath("//a[@class='s-city']")).getText();
            int pageCount = getPageCount();
            parsePriceElement();
            for (int i = 2; i <= pageCount; i++) {
                if (alreadyCount < CONTRAST_COUNT) {
                    WebElement nextElement = webDriver.findElement(By.xpath("//a[@class='next']"));
                    Actions action = new Actions(webDriver);
                    action.moveToElement(nextElement).click(nextElement).build().perform();

                    WebElement nextElement1 = webDriver.findElement(By.xpath("//a[@class='next']"));
                    Actions action1 = new Actions(webDriver);
                    action1.moveToElement(nextElement1).build().perform();

                    sleep(3000);
                    parsePriceElement();
                } else {
                    break;
                }
            }
            analyseData();
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return null;
    }

    private int getPageCount() {
        int lastPage = 0;
        String strPage = webDriver.findElement(By.xpath("//div[@class='page-box']")).getAttribute("data-total-count");
        lastPage = Integer.parseInt(strPage) / 10;
        return lastPage;
    }

    private void parsePriceElement() {
        List<WebElement> liElementList = webDriver.findElement(By.xpath("//ul[@class='resblock-list-wrapper']")).findElements(By.tagName("li"));
        for (WebElement liElement: liElementList) {
            if (alreadyCount >= CONTRAST_COUNT) {
                break;
            }
            try {
                String price = liElement.findElement(By.xpath(".//span[@class='number']")).getText();
                String desc = liElement.findElement(By.xpath(".//span[@class='desc']")).getText();
                if (!desc.contains("总价")) {
                    alreadyCount++;
                    System.out.println(String.format("%s 第%d个， 价格：%s    描述:%s", currentCityName, alreadyCount, price, desc));
                    priceList.add(Integer.parseInt(price));
                }
            } catch (Exception e) {
//                e.printStackTrace();
            }


        }
        sleep(2000);
    }

    @Override
    public void close() throws IOException {

    }

    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拿到100个样本数据，去掉25个最大值和25个最小值，然后剩余60个取平均数
     */
    private void analyseData() {
        Collections.sort(priceList);
        int total = priceList.size();
        int startIndex = total / 4;
        int endIndex = total - startIndex;
        int count = 0;
        int sum = 0;
        for (int i = startIndex; i < endIndex; i++) {
            count++;
            sum += priceList.get(i);
        }
        String result = String.format("%s取了%s个数据得到的平均价是%s", currentCityName, priceList.size(), (sum / count));
        resultList.add(result);
    }
}
